import 'dart:async';

import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_rank.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/pool_list_model.dart';
import 'package:gold/model/pool_model.dart';

/// @description: 排行榜
/// @author tangzhentao
/// @created at 21:05 2024/12/1

class RankContentViewmodel extends Viewmodel {
  /// 类型
  final PoolType _poolType;

  /// 选中类型下标
  bool _showMore = false;
  bool get showMore => _showMore;
  set showMore(bool value) {
    if (_showMore != value) {
      _showMore = value;
      notifyListeners();
    }
  }

  /// 开奖时间
  String? prizeDrawTime = '';

  Timer? _timer;

  /// 奖池信息
  PoolModel? pool;
  /// 排行列表
  final List<PoolRankModel> list = [];
  /// 我的排行
  PoolRankModel? mimeRankModel;

  RankContentViewmodel(this._poolType);

  /// 加载数据
  Future load() async {
    setLoading();
    final poolResult = await Http().request<PoolModel>(ApiRank.poolInfo,
        data: {'type': _poolType.type}, showErrorMsg: false);
    if (poolResult.success) {
      pool = poolResult.data;
      if (pool != null) {
        if (pool!.id != null) {
          final listResult = await Http().request<PoolListModel>(ApiRank.poolRank,
              data: {'id': pool!.id, 'page': 1}, showErrorMsg: false);
          final mimeResult = await Http().request<PoolRankModel>(ApiRank.poolMine,
              data: {'id': pool!.id}, showErrorMsg: false);
          list.addAll(listResult.data?.data?? []);
          mimeRankModel = mimeResult.data;
          _startTimer();
          setSuccess();
        } else {
          setFailed(msg: '奖池id异常');
        }
      } else {
        setEmpty(msg: '奖池信息为空');
      }
    } else {
      setFailed(msg: poolResult.msg);
    }
  }

  /// 开启计时器
  void _startTimer() {
    final end = DateTime.tryParse(pool?.endTime?? '');
    if (end != null) {
      double seconds = (end.millisecondsSinceEpoch - DateTime.now().millisecondsSinceEpoch) / 1000;
      if (seconds <= 0) {
        prizeDrawTime = null;
      } else {
        prizeDrawTime = _getPrizeDrawTime(seconds);
        _timer = Timer.periodic(const Duration(minutes: 1), (_) {
          seconds = seconds - 60;
          if (seconds <= 0) {
            prizeDrawTime = null;
          } else {
            prizeDrawTime = _getPrizeDrawTime(seconds);
          }
          notifyListeners();
        });
      }
    }
  }

  /// 获取截止时间
  String _getPrizeDrawTime(double seconds) {
    final days = (seconds / (24 * 60 * 60)).toInt();
    final reHours = seconds % (24 * 60 * 60);
    final hours = (reHours / 3600).toInt();
    final reMinutes = reHours % 3600;
    final minutes = (reMinutes / 60).toInt();
    return '${days > 0 ? '$days天':''}${hours > 0 ? '$hours时':''}${minutes > 0 ? '$minutes分':''}';
  }

  /// 停止计时器
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  onReload() => load();

  @override
  onRetry() => load();

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }
}

enum PoolType {
  day(name: '日', type: 'day'),
  week(name: '周', type: 'week'),
  month(name: '月', type: 'month'),
  year(name: '年', type: 'year');

  const PoolType({required this.name, required this.type});
  final String name;
  final String type;
}
